package com.mdp.im.core.ctrl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.mdp.core.utils.BaseUtils;
import com.mdp.im.core.entity.ImGroupUser;
import com.mdp.im.core.vo.GroupVo;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.entity.LangTips;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;

import com.mdp.im.core.service.ImGroupService;
import com.mdp.im.core.entity.ImGroup;
/**
 * @author 唛盟开源 code-gen
 * @since 2024-8-13
 */
@RestController
@RequestMapping(value="/mdp/im/core/imGroup")
@Api(tags={"群聊-操作接口"})
public class ImGroupController {
	
	static Logger logger =LoggerFactory.getLogger(ImGroupController.class);
	
	@Autowired
	private ImGroupService imGroupService;

	@Operation( summary =  "群聊-查询列表")
	@ApiEntityParams(ImGroup.class)
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listImGroup(  @RequestParam Map<String,Object> params){
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<ImGroup> qw = QueryTools.initQueryWrapper(ImGroup.class , params);
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = imGroupService.selectListMapByWhere(page,qw,params);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
	}
	

	@Operation( summary =  "群聊-新增")
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addImGroup(@RequestBody ImGroup imGroup) {
		 imGroupService.save(imGroup);
         return Result.ok("add-ok","添加成功！").setData(imGroup);
	}

	@Operation( summary =  "群聊-删除")
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delImGroup(@RequestBody ImGroup imGroup){
		imGroupService.removeById(imGroup);
        return Result.ok("del-ok","删除成功！");
	}

	@Operation( summary =  "群聊-修改")
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editImGroup(@RequestBody ImGroup imGroup) {
		imGroupService.updateById(imGroup);
        return Result.ok("edit-ok","修改成功！");
	}

    @Operation( summary =  "群聊-批量修改某些字段" )
    @ApiEntityParams( value = ImGroup.class, props={ }, remark = "群聊", paramType = "body" )
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields(   @RequestBody Map<String,Object> params) {
            User user= LoginUtils.getCurrentUserInfo();
            imGroupService.editSomeFields(params);
            return Result.ok("edit-ok","更新成功");
	}

	@Operation( summary =  "群聊-批量删除")
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelImGroup(@RequestBody List<ImGroup> imGroups) {
	    User user= LoginUtils.getCurrentUserInfo();
        if(imGroups.size()<=0){
            return Result.error("batchDel-data-err-0","请上送待删除数据列表");
        }
         List<ImGroup> datasDb=imGroupService.listByIds(imGroups.stream().map(i-> i.getId() ).collect(Collectors.toList()));

        List<ImGroup> can=new ArrayList<>();
        List<ImGroup> no=new ArrayList<>();
        for (ImGroup data : datasDb) {
            if(true){
                can.add(data);
            }else{
                no.add(data);
            }
        }
        List<String> msgs=new ArrayList<>();
        if(can.size()>0){
            imGroupService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
        }

        if(no.size()>0){
            msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
        }
        if(can.size()>0){
             return Result.ok(msgs.stream().collect(Collectors.joining()));
        }else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
	} 

	@Operation( summary =  "群聊-根据主键查询一条数据")
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(ImGroup imGroup) {
        ImGroup data = (ImGroup) imGroupService.getById(imGroup);
        return Result.ok().setData(data);
    }

    //查询所有我所在的群,不关联聊天
    @RequestMapping(value="/listMyChannelGroupsOnly",method=RequestMethod.GET)
    public Result listMyChannelGroupsOnly( @RequestParam Map<String,Object> imGroup){
        Map<String,Object> m = new HashMap<>();
        List<Map<String,Object>>	imGroupList = imGroupService.listMyGroupsOnly((String)imGroup.get("branchId"), (String)imGroup.get("userid"));	//列出ImGroup列表

        return Result.ok().setData(imGroupList);
    }

    @ApiOperation( value = "查询所有我所在的群",notes="userid 用户编号")
    @RequestMapping(value="/listMyChannelGroups",method=RequestMethod.GET)
    public Result listMyChannelGroups( @RequestParam Map<String,Object> imGroup){
        //将时间戳转化为日期格式 如 2020-03-25 12：12：12
        String lastLoadImDataTime = (String)imGroup.get("lastLoadImDataTime");
        if(lastLoadImDataTime != null && !lastLoadImDataTime.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(new Date(Long.valueOf(lastLoadImDataTime)));
            imGroup.put("lastLoadImDataTime",format);
        }

        List<Map<String,Object>>	imGroupList = imGroupService.listMyGroups((String)imGroup.get("branchId"), (String)imGroup.get("userid"),(String)imGroup.get("lastLoadImDataTime"));	//列出ImGroup列表


        return Result.ok().setData(imGroupList).setTotal(imGroupList.size());
    }
    @ApiOperation( value = "查询一个群的信息及其用户列表",notes="groupId 群编号")
    @RequestMapping(value="/queryGroupAndUsers",method=RequestMethod.GET)
    public Result queryGroupAndUsers( @RequestParam Map<String,Object> imGroup){
        Map<String,Object> m = new HashMap<>();
        GroupVo group = imGroupService.queryGroupAndUsers((String)imGroup.get("branchId"), (String)imGroup.get("groupId"));	//列出ImGroup列表
        return Result.ok().setData(group);
    }

    @RequestMapping(value="/addGruopAndUser",method=RequestMethod.POST)
    public Result addGruopAndUser(@RequestBody Map<String,Object> params) {
            List imGroupUser = (List)params.get("group");
            ImGroup imGroup = new ImGroup();
            String imGroupid=imGroupService.createKey("id");
            imGroup.setId(imGroupid);
            imGroup.setGroupName((String) params.get("cusername")+"创建的普通群聊");
            imGroup.setCategoryId("COMMON");
            imGroup.setCuserid((String) params.get("cuserid"));
            imGroup.setCusername((String) params.get("cusername"));
            imGroup.setBizStatus("0");
            imGroup.setGstatus("1");
            imGroup.setAllowJoin("1");
            imGroup.setCdate(new Date());
//			imGroup.setCdate(new Date());
//			for(ImGroupUser user:imGroupUser){
//				user.setGroupId(imGroupid);
//			}
            ArrayList<ImGroupUser> imGroupUsers = new ArrayList<ImGroupUser>();//放用户数组
            for(int i=0;i<imGroupUser.size();i++){
                Map map = (Map)imGroupUser.get(i);
                ImGroupUser groupUser = BaseUtils.fromMap(map, ImGroupUser.class);
                groupUser.setGroupId(imGroupid);
                imGroupUsers.add(groupUser);
            }
            imGroupService.asyncCreateGroupAndBatchInsertUsers(imGroup,imGroupUsers);
            return Result.ok().setData(imGroup);

    }
}
